package peer.p2pnet.message;

import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.HashMap;

import peer.Message;
import peer.p2pnet.DBNode;
import peer.p2pnet.DBNodeIdent;
import peer.tools.ByteIntSwitch;
import peer.tools.ByteShortSwitch;
import peer.tools.Mdb;
import server.Config;
import server.Group;

public class PubDelMessage2 extends Message{
	public short sType=peer.tools.MessageType.sType_PubDelMessage2;
	Group group;
	byte[] castMemberByte;
	short memberNum;
	byte[] dpData;
	HashMap<DBNodeIdent, DBNode> castMemberTable;
	public PubDelMessage2(Mdb mdb){
		group=(Group)Config.groupMange.getGroup(mdb);
		if(group!=null){
			memberNum=(short) group.castMemberTable.size();
			castMemberByte=group.getMemberByte();
			dpData=new byte[6+castMemberByte.length];
		}else{
			memberNum=0;
			castMemberByte=new byte[0];
			dpData=new byte[6+castMemberByte.length];
		}
		
		ByteShortSwitch.toByteArray(ver, dpData, 0);  //add: ver
		ByteShortSwitch.toByteArray(sType, dpData, 2);  //add: service type
		ByteShortSwitch.toByteArray(memberNum, dpData, 4);
		System.arraycopy(castMemberByte, 0, dpData, 6, castMemberByte.length);
		dp=new DatagramPacket(dpData,dpData.length);
	}
	
	public PubDelMessage2(DatagramPacket dp,Mdb mdb){
		this.dp=dp;
		dpData=dp.getData();
		ver=ByteShortSwitch.toShort(dpData, 0);
		sType=ByteShortSwitch.toShort(dpData, 2);
		memberNum=ByteShortSwitch.toShort(dpData, 4);
		castMemberTable=new HashMap<DBNodeIdent, DBNode>();
		for(int i=0;i<memberNum;i++){
			byte[] ip2=new byte[4];
			InetAddress ip=null;
			System.arraycopy(dpData, 6+i*8, ip2, 0, 4);
			try {
				ip=InetAddress.getByAddress(ip2);
			} catch (UnknownHostException e) {
				e.printStackTrace();
			}
			int DBServerPort=ByteIntSwitch.toInt(dpData, 6+i*8+4);
			DBNodeIdent ni=new DBNodeIdent(ip,DBServerPort);
			DBNode n=new DBNode(mdb,ip,DBServerPort);
			castMemberTable.put(ni,n);
		}
	}
	
	public HashMap<DBNodeIdent, DBNode> getCastMemberTable(){
		return castMemberTable;
	}

}
